<template>
  <div>
    <el-drawer
      :visible.sync="visible"
      :with-header="false"
      size="32%"
    >
      <div style="margin-top: 2%">
        <el-row type="flex" style="align-items: center">
          <el-col :span="18"><el-divider>下载中心</el-divider></el-col>
          <el-col :span="2"><span /></el-col>
          <el-col :span="4"><el-button :type="startAll ? 'info' : 'success'" @click="onTriggerStart">{{ startAll ? '全部暂停' : '全部开始' }}</el-button></el-col>
        </el-row>
      </div>
      <div v-for="(item, index) in localStorageArray" :key="index" style="margin: 1%">
        <el-card shadow="hover">
          <el-row type="flex" style="align-items: center">
            <el-col :span="item.isSuccess ? 24 : 20">
              <el-tooltip class="item" effect="light" :content="item.fileName" placement="top">
                <span class="wrap">
                  {{ item.fileName }}
                </span>
              </el-tooltip>
            </el-col>
            <el-col v-if="!item.isSuccess" :span="4">
              <el-dropdown trigger="click">
                <el-button type="success" icon="el-icon-more-outline" />
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button
                      type="text"
                      style="color: #00a0e9"
                      :icon="item.isPause ? 'el-icon-download' : 'el-icon-video-pause'"
                      @click="downloadMp4(item)"
                    >{{ item.isPause ? '下载' : '暂停' }}</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-popconfirm title="是否取消下载文件" @confirm="removeDownload(item)">
                      <el-button slot="reference" style="color: #DC5350" color="danger" type="text" icon="el-icon-delete">删除</el-button>
                    </el-popconfirm>
                  </el-dropdown-item>
                  <!--                  <el-dropdown-item>-->
                  <!--                    <el-button-->
                  <!--                      v-permission="['admin','spiderVideo:list']"-->
                  <!--                      style="color: blueviolet"-->
                  <!--                      type="text"-->
                  <!--                      @click="item.isSuccess"-->
                  <!--                    >重新下载错误片段-->
                  <!--                    </el-button>-->
                  <!--                  </el-dropdown-item>-->
                  <el-dropdown-item>
                    <el-button
                      v-permission="['admin','spiderVideo:list']"
                      icon="el-icon-warning-outline"
                      style="color: #FFBA00"
                      type="text"
                      @click="forceDownload(item)"
                    >强制下载现有片段
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <el-row style="margin-top: 2%">
            <el-col>
              <el-progress :percentage="parseInt(item.percentage || 0)" :color="customColors" />
            </el-col>
          </el-row>
        </el-card>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { getDownloadManageItem, setDownloadManageArray, spiderConst } from '@/utils/spiderUtil'
import { DownloaderUtil } from '@/utils/DownloaderUtil'

export default {
  name: 'VideoDownloader',
  data() {
    return {
      startAll: false,
      downloadMap: new Map(),
      spiderConst: spiderConst,
      localStorageArray: [],
      visible: false,
      downloadList: [],
      customColors: [
        { color: '#0ebeff', percentage: 10 },
        { color: '#24b3f8', percentage: 20 },
        { color: '#3aa7f1', percentage: 30 },
        { color: '#509cea', percentage: 40 },
        { color: '#6691e3', percentage: 50 },
        { color: '#7c86dc', percentage: 60 },
        { color: '#917ad6', percentage: 70 },
        { color: '#a76fcf', percentage: 80 },
        { color: '#bd64c8', percentage: 90 },
        { color: '#d359c1', percentage: 100 }
      ]
    }
  },

  created() {
    this.init()
  },

  beforeDestroy() {
    this.refreshDownloadList()
  },
  methods: {
    getDownloadManageItem,
    setDownloadManageArray,
    onTriggerStart() {
      this.startAll = !this.startAll
      const downloadList = this.downloadMap.values().filter(item => !item.isSuccess)
      for (let i = 0; i < downloadList.length; i++) {
        if (this.startAll) {
          downloadList[i].retryAll((obj) => {
            downloadList[i] = Object.assign(downloadList[i], obj)
            this.refreshDownloadList()
          })
        } else {
          downloadList[i].pause()
        }
      }
    },
    forceDownload(item) {
      if (this.downloadMap.has(item.id)) {
        this.downloadMap.get(item.id).forceDownload((obj) => {
          item = Object.assign(item, obj)
          this.refreshDownloadList()
        })
      }
    },
    retryAll(item) {
      if (this.downloadMap.has(item.id)) {
        this.downloadMap.get(item.id).retryAll((obj) => {
          item = Object.assign(item, obj)
          this.refreshDownloadList()
        })
      }
    },
    removeDownload(data) {
      const arr = []
      for (let i = 0; i < this.localStorageArray.length; i++) {
        if (this.localStorageArray[i].url !== data.url && this.localStorageArray[i].fileName !== data.fileName) {
          arr.push(Object.assign({}, this.localStorageArray[i]))
        }
      }
      this.localStorageArray = [...arr]
      // 删除下载器的对象下载
      if (this.downloadMap.has(data.id)) {
        this.downloadMap.get(data.id).removeDownload()
        this.downloadMap.delete(data.id)
      }
      this.refreshDownloadList()
    },
    refreshDownloadList() {
      this.setDownloadManageArray(this.localStorageArray)
    },
    addDownloadData(data) {
      this.refreshDownloadList()
      if (this.localStorageArray && this.localStorageArray.length === 0) {
        this.localStorageArray = []
        const downloadUtil = new DownloaderUtil(Object.assign({}, data), this)
        this.downloadMap.set(downloadUtil.id, downloadUtil)
        this.localStorageArray.push(downloadUtil)
        this.refreshDownloadList()
      } else {
        const filter = this.localStorageArray.filter((item) => {
          return item.url === data.url || item.fileName === data.fileName
        })
        if (filter.length > 0) {
          this.$message.error('下载中心已存在该记录')
        } else {
          const downloadUtil = new DownloaderUtil(Object.assign({}, data), this)
          this.downloadMap.set(downloadUtil.id, downloadUtil)
          this.localStorageArray.push(downloadUtil)
          this.refreshDownloadList()
          this.$message.success('已加入下载队列')
        }
      }
    },
    init() {
      const _this = this
      if (!this.localStorageArray || this.localStorageArray.length === 0) {
        let downloadManageItem = this.getDownloadManageItem()
        if (downloadManageItem && downloadManageItem !== 'undefined' && downloadManageItem.length > 0) {
          downloadManageItem = JSON.parse(downloadManageItem)
          downloadManageItem.forEach(item => {
            const downloadUtil = new DownloaderUtil(Object.assign({}, item), _this)
            this.downloadMap.set(downloadUtil.id, downloadUtil)
            _this.localStorageArray.push(downloadUtil)
          })
        }
      }
    },
    downloadMp4(item) {
      if (this.downloadMap.has(item.id)) {
        const downloaderUtil = this.downloadMap.get(item.id)
        item.isPause = !item.isPause
        downloaderUtil.isPause = item.isPause
        !downloaderUtil.isPause && downloaderUtil.downloadMp4((obj) => {
          item = Object.assign(item, obj)
          this.refreshDownloadList()
        })
      }
    }
  }
}
</script>

<style>
.wrap {
  word-break: break-all;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  line-height: 30px;
  overflow-y: hidden;
}
</style>
